<template>
  <div class="m-usedMachine">
    <div class="mescroll-region" ref="mescroll">
      <!-- 面包屑 -->
      <div class="bread-crumb m-container">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item>{{ $t("yunLianUsedMachine") }}</el-breadcrumb-item>
          <el-breadcrumb-item>{{
            locale == "en-US" ? $optionsData.equipmentTypeBreadcrumb[this.typeId] : $optionsData.equipmentTypeHz[this.typeId]
          }}</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <!-- 设备筛选 -->
      <div class="change-box m-container">
        <el-dropdown class="filter-item" trigger="click">
          <span class="el-dropdown-link"> {{ $t("category") }}<i class="el-icon-arrow-down el-icon--right"></i> </span>
          <el-dropdown-menu slot="dropdown">
            <a
              :class="[typeId == item.id ? 'selected-item' : 'select-item']"
              v-for="item in typeList"
              :key="item.id"
              :href="`/m-used-machine/${$optionsData.equipmentTypePy[item.id]}-${item.id}`"
              :title="item.name"
              @click="numSelectType"
            >
              <el-dropdown-item>{{ item.name }}</el-dropdown-item>
            </a>
          </el-dropdown-menu>
        </el-dropdown>
        <el-dropdown class="filter-item" trigger="click" v-if="locale == 'zh-CN'">
          <span class="el-dropdown-link"> 区域<i class="el-icon-arrow-down el-icon--right"></i> </span>
          <el-dropdown-menu slot="dropdown">
            <span
              :class="[areaId == item.code ? 'selected-item' : 'select-item']"
              v-for="item in $optionsData.provinceList"
              :key="item.code"
              @click="numSelectArea(item.code)"
            >
              <el-dropdown-item>{{ item.text }}</el-dropdown-item>
            </span>
          </el-dropdown-menu>
        </el-dropdown>
        <el-dropdown class="filter-item" trigger="click" v-for="item in attrsList" :key="item.title">
          <span class="el-dropdown-link"> {{ item.title }}<i class="el-icon-arrow-down el-icon--right"></i> </span>
          <el-dropdown-menu slot="dropdown">
            <span
              :class="[val.checked ? 'selected-item' : 'select-item']"
              v-for="(val, index) in item.options"
              :key="val.value"
              @click="selectTem(item.title, index)"
            >
              <el-dropdown-item>{{ val.name }}</el-dropdown-item>
            </span>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
      <!-- 设备列表 -->
      <section class="equipment-list m-container">
        <template v-if="equipmentList.length">
          <a
            class="equipment-item"
            v-for="item in equipmentList"
            :key="item.crmEquipmentId"
            :href="`/m-equipment/${item.typeNameEn}-${item.crmEquipmentId}`"
            :title="`${item.title} | ${item.subHeading}`"
            @click="handleDetail"
          >
            <el-image class="info-img" fit="cover" :src="item.thumbnail" lazy :alt="item.title"></el-image>
            <div class="info-bottom">
              <div class="info-title">{{ item.title }}</div>
              <div class="info-year">{{ item.subHeading }}</div>
              <div class="info-tag" v-if="locale == 'zh-CN'">
                <p v-for="val in item.targerList" :key="val">{{ val }}</p>
              </div>
              <div style="height: 18px" v-else></div>
              <div class="info-price">
                <template v-if="item.crmEquipmentFixedPriceId && item.offlineBargaining != 1">
                  <p v-if="locale == 'en-US'">CNY{{ item.startingPriceNotag }}</p>
                  <p v-else>{{ item.startingPrice / 1000000 }}万</p>
                </template>
                <p v-else>{{ $t("priceNegotiable") }}</p>
              </div>
            </div>
          </a>
        </template>
        <div class="no-data" v-else>
          <div class="no-pic">
            <img class="pic-empty" src="https://yunlian-oss-product.oss-cn-hangzhou.aliyuncs.com/website/pic-empty.png" />
            <p>{{ $t("noListingsFound") }}</p>
          </div>
          <a class="help-car" href="/m-find-car" :title="`${$t('findMachine')}`">{{ $t("findMachine") }}</a>
        </div>
      </section>
    </div>
    <!-- WhatsApp -->
    <!-- <WhatsAppM v-if="locale == 'en-US'" /> -->
  </div>
</template>

<script>
import { mapState } from "vuex"
import BigNumber from "bignumber.js"
export default {
  name: "M-usedMachine",
  layout: "mobile",
  data() {
    return {
      phoneIcon: "https://yunlian-oss-product.oss-cn-hangzhou.aliyuncs.com/website/no-more.png",
      mescroll: null
    }
  },
  head() {
    return {
      title: this.$i18n.t("headTitle"),
      meta: [
        {
          hid: "keywords",
          name: "keywords",
          content: this.$i18n.t("haeaKeyContent")
        },
        {
          hid: "description",
          name: "description",
          content: this.$i18n.t("haeaDecContent")
        }
      ]
    }
  },
  async asyncData({ app, params }) {
    let paramsRes = params.typeParams.split("-")
    console.log("paramsRes", paramsRes)
    let pageSizeNum = 16
    let typeId = paramsRes[1] //设备类型ID
    let areaId = paramsRes[2] || "" //区域ID
    let typeList = []
    let attrsList = []
    let equipmentList = []
    let tonnageName = ""
    let yearsName = ""
    let workingHoursName = ""
    let batchNumName = ""
    let armSpanName = ""
    try {
      if (app.$cookies.get("msgInfo") && !!app.$cookies.get("searchCondition")) {
        let data = app.$cookies.get("searchCondition")
        typeId = data[0].typeId
        areaId = data[0].areaId
        tonnageName = data[0].tonnageName
        yearsName = data[0].yearsName
        workingHoursName = data[0].workingHoursName
        batchNumName = data[0].batchNumName
        armSpanName = data[0].armSpanName
        attrsList = data[1]
      } else {
        app.$cookies.remove("searchCondition")
        //筛选-模板
        let configRes = await app.$api.searchConfig({ typeId: typeId })
        attrsList = configRes.data && configRes.data.cardList ? configRes.data.cardList[0].attrs : []
      }
      //设备机型
      let typeRes = await app.$api.machineType()
      typeList = typeRes.data || []
      //设备列表
      const equipmentParams = {
        pageNo: 1,
        pageSize: pageSizeNum,
        search: {
          typeId: typeId,
          provinceCodes: [areaId || 100000],
          tonnageName: tonnageName,
          yearsName: yearsName,
          workingHoursName: workingHoursName,
          batchNumName: batchNumName,
          armSpanName: armSpanName
        }
      }
      let { data } = await app.$api.equipmentList(equipmentParams)
      equipmentList = (data.list || []).map((item) => {
        item.startingPriceNotag = new BigNumber(item.startingPrice).dividedBy(100).toFormat()
        let targerList = app.$optionsData.parseLabel(item)
        if (targerList.indexOf("寄售") != -1) {
          targerList.splice(targerList.indexOf("寄售"), 1)
        }
        targerList = targerList.splice(0, 2)
        item["targerList"] = targerList
        return item
      })
    } catch (error) {
      console.log(error)
    }
    return {
      pageSizeNum,
      equipmentList, //设备列表
      typeId, //设备类型-筛选
      areaId, //区域-筛选
      typeList, //设备类型列表
      attrsList, //筛选模板列表
      tonnageName, //吨位筛选
      yearsName, //年限筛选
      workingHoursName, //小时数筛选
      batchNumName, //批量数筛选
      armSpanName //臂展长度筛选
    }
  },
  props: {},
  computed: { ...mapState(["locale"]) },
  async mounted() {
    this.getPoint()
    // 创建MeScroll对象：为避免配置的id和父组件id重复，这里使用ref的方式初始化mescroll
    this.mescroll = new this.$mescroll(this.$refs.mescroll, {
      // 初始化mescroll,以确保您配置的dom元素能够被找到
      up: {
        auto: true, // 是否在初始化时以上拉加载的方式自动加载第一页数据
        callback: this.upCallback, // 此处可简写，相当于 callback: function (page) { upCallback(page) }
        page: {
          num: 0, //当前页 默认0,回调之前会加1; 即callback(page)会从1开始
          size: 16 //每页数据条数,默认16
        },
        noMoreSize: 5, //如果列表已无数据,可设置列表的总数量要大于5才显示无更多数据
        htmlLoading: `<p class="upwarp-progress mescroll-rotate"></p><p class="upwarp-tip">${this.$i18n.t("loading")}..</p>`, //上滑加载loading文案
        htmlNodata: `<p class="upwarp-nodata"><img src="${this.phoneIcon}" /><span>${this.$i18n.t("noMore")}</span></p>` //不配置页面底部无数据提示
      },
      down: {
        textOutOffset: `${this.$i18n.t("releaseUpdates")}`, //下拉刷新loading文案
        textLoading: `${this.$i18n.t("loading")}` //下拉刷新loading文案
      }
    })
  },
  destroyed() {
    this.$cookies.remove("msgInfo") //清除检索存储值
  },
  methods: {
    // 类型筛选
    numSelectType() {
      this.$cookies.remove("msgInfo") //清除检索存储值
    },
    // 区域筛选
    numSelectArea(val) {
      this.areaId = this.areaId != val ? val : ""
      this.mescroll.resetUpScroll()
    },
    selectTem(title, index) {
      let list = this.attrsList
      for (let i = 0; i < list.length; i++) {
        for (let j = 0; j < list[i].options.length; j++) {
          if (list[i].title == title) {
            if (j == index) {
              if (list[i].options[j].checked == true) {
                list[i].options[j].checked = false
                if (title == "出厂年限" || title == "Factory Years") {
                  this.yearsName = ""
                } else if (title == "表显小时数" || title == "Meter display hours") {
                  this.workingHoursName = ""
                } else if (title == "吨位" || title == "起重总量" || title == "Tonnage" || title == "Total lifting capacity") {
                  this.tonnageName = ""
                } else if (title == "批量数" || title == "Batch quantity") {
                  this.batchNumName = ""
                } else if (title == "臂架长度" || title == "Arm length") {
                  this.armSpanName = ""
                }
              } else {
                list[i].options[j].checked = true
                if (title == "出厂年限" || title == "Factory Years") {
                  this.yearsName = list[i].options[j].value
                } else if (title == "表显小时数" || title == "Meter display hours") {
                  this.workingHoursName = list[i].options[j].value
                } else if (title == "吨位" || title == "起重总量" || title == "Tonnage" || title == "Total lifting capacity") {
                  this.tonnageName = list[i].options[j].value
                } else if (title == "批量数" || title == "Batch quantity") {
                  this.batchNumName = list[i].options[j].value
                } else if (title == "臂架长度" || title == "Batch quantity") {
                  this.armSpanName = list[i].options[j].value
                }
              }
            } else {
              list[i].options[j].checked = false
            }
          }
        }
      }
      this.attrsList = list
      this.$forceUpdate()
      this.mescroll.resetUpScroll()
    },
    // 上拉加载回调
    upCallback(page) {
      // console.log("upCallback", page)
      this.getListDataFromNet(
        page.num,
        page.size,
        (curPageData) => {
          if (page.num == 1) {
            this.equipmentList = curPageData
          } else {
            this.equipmentList = this.equipmentList.concat(curPageData)
          }
          this.$nextTick(() => {
            this.mescroll.endSuccess(curPageData.length)
          })
        },
        () => {
          this.mescroll.endErr()
        }
      )
    },
    async getListDataFromNet(pageNum, pageSize, successCallback, errorCallback) {
      const params = {
        pageNo: pageNum,
        pageSize: pageSize,
        search: {
          typeId: this.typeId,
          provinceCodes: [this.areaId || 100000],
          tonnageName: this.tonnageName,
          yearsName: this.yearsName,
          workingHoursName: this.workingHoursName,
          batchNumName: this.batchNumName,
          armSpanName: this.armSpanName
        }
      }
      try {
        let {
          data: { list }
        } = await this.$api.equipmentList(params)
        let equipmentList = (list || []).map((item) => {
          item.startingPriceNotag = new BigNumber(item.startingPrice).dividedBy(100).toFormat()
          let targerList = this.$optionsData.parseLabel(item)
          if (targerList.indexOf("寄售") != -1) {
            targerList.splice(targerList.indexOf("寄售"), 1)
          }
          targerList = targerList.splice(0, 2)
          item["targerList"] = targerList
          return item
        })
        successCallback && successCallback(equipmentList)
      } catch (e) {
        errorCallback && errorCallback()
      }
    },
    handleDetail() {
      let storageData = {
        typeId: this.typeId,
        areaId: this.areaId,
        tonnageName: this.tonnageName,
        yearsName: this.yearsName,
        workingHoursName: this.workingHoursName,
        batchNumName: this.batchNumName,
        armSpanName: this.armSpanName
      }
      this.$cookies.set("searchCondition", JSON.stringify([storageData, this.attrsList])) //存储搜索条件
    },
    async getPoint() {
      let params = await this.$optionPoint.sendUrl(window, navigator, document)
      this.$api.burySave({ ...params }).then((res) => {})
    }
  }
}
</script>

<style lang="scss" scoped>
.el-dropdown-menu {
  max-height: 1600px;
  overflow: scroll;
  .selected-item {
    ::v-deep .el-dropdown-menu__item {
      color: #fb463f;
    }
  }
}
.m-usedMachine {
  .mescroll-region {
    width: 100%;
    position: fixed;
    top: 225px;
    bottom: 0;
    overflow-y: auto;
    margin-bottom: 300px;
    ::v-deep .upwarp-nodata {
      display: flex;
      align-items: center;
      justify-content: center;
      img {
        width: 108px;
        height: 82px;
        margin-right: 20px;
      }
      span {
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        font-size: 61px;
        color: #999;
      }
    }
    .bread-crumb {
      margin-top: 80px;
    }
    .change-box {
      .filter-item {
        margin-top: 80px;
        margin-right: 60px;
      }
    }
    .equipment-list {
      display: flex;
      justify-content: space-between;
      flex-wrap: wrap;
      margin-top: 80px;
      .equipment-item {
        width: 860px;
        height: 100%;
        margin-bottom: 50px;
        .info-img {
          width: 860px;
          height: 543px;
          display: block;
        }
        .info-bottom {
          width: 100%;
          height: 486px;
          background: #f6f7f9;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          padding: 50px;
          box-sizing: border-box;
          .info-title {
            font-family: PingFangSC, PingFang SC;
            font-weight: 500;
            font-size: 72px;
            color: #333;
            line-height: 92px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
          .info-year {
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            font-size: 60px;
            color: #999;
            line-height: 80px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
          .info-tag {
            display: flex;
            align-items: center;
            p {
              height: 60px;
              line-height: 60px;
              padding: 10px;
              border-radius: 12px;
              font-family: PingFangSC, PingFang SC;
              font-weight: 400;
              font-size: 40px;
              color: #fb463f;
              background: rgba(251, 70, 63, 0.08);
              margin-right: 30px;
            }
          }
          .info-price {
            display: flex;
            align-items: flex-end;
            flex-direction: row;
            justify-content: space-between;
            p {
              font-size: 82px;
              font-weight: 700;
              color: #fb463f;
            }
          }
        }
      }
      .no-data {
        width: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        margin-top: 500px;
        .no-pic {
          .pic-empty {
            width: 1172px;
            height: 768px;
          }
          p {
            font-family: PingFangSC, PingFang SC;
            font-weight: 600;
            font-size: 82px;
            color: #333;
            line-height: 92px;
            margin-top: 50px;
            text-align: center;
          }
        }
        .help-car {
          width: 768px;
          height: 205px;
          line-height: 205px;
          text-align: center;
          background: #d71519;
          font-family: PingFangSC, PingFang SC;
          font-weight: 500;
          font-size: 72px;
          color: #fff;
          margin-top: 102px;
        }
      }
    }
  }
}
</style>
